package com.zhu.storesmanager.security;

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;

public class RsaUtil {
	public static String rsaEncrypt(String str_exponent, String str_modulus,String content) {
		try
		{
			// 创建公钥
			byte[] ary_exponent = (new BASE64Decoder()).decodeBuffer(str_exponent);
			byte[] ary_modulus = (new BASE64Decoder()).decodeBuffer(str_modulus);
			// 注意构造函数，调用时指明正负值，1代表正值，否则报错
			BigInteger big_exponent = new BigInteger(1, ary_exponent);
			BigInteger big_modulus = new BigInteger(1, ary_modulus);
			RSAPublicKeySpec keyspec = new RSAPublicKeySpec(big_modulus, big_exponent);
			KeyFactory keyfac = KeyFactory.getInstance("RSA");
			PublicKey publicKey = keyfac.generatePublic(keyspec);

			// 进行加密
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] enBytes = cipher.doFinal(content.getBytes("UTF-8"));
			String s = (new BASE64Encoder()).encodeBuffer(enBytes);
			//System.out.println("加密结果为：" + s);

			return s;
		}
		catch(Exception e)
		{
			return null;
		}
		
	}

}
